#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os

from PyQt4 import QtCore, QtGui
import ui_go_edit

class Form(QtGui.QDialog, ui_go_edit.Ui_Form):

    _CODE = 'code'
    _ERR = 'err'
    _RESULT = 'result'
    
    def __init__(self, parent=None):
        super(Form, self).__init__(parent)
        self.setupUi(self)

        self.connect(self.compileBtn, QtCore.SIGNAL("clicked()"), 
                     self.process)
        
        # try to load code exist to textEdit.
        self.load()

    def load(self):
    	if(os.path.isfile('{code}.go'.format(code = self._CODE))):
    	    content = open('{code}.go'.format(code = self._CODE)).read()
    	    self.textEdit.setText(content)
    	else:
    	    pass

    def process(self):
        self.save()
        self.compile()
        self.run()
        self.display()
        self.clean()

    def save(self):
        file = open('{code}.go'.format(code = self._CODE), 'w')
        text = self.textEdit.toPlainText()
        file.write(text)
        file.close()

    def compile(self):
        os.system(
            '8g {code}.go 1> {err}'.format(
                code = self._CODE, 
                err = self._ERR
            )
        )
        os.system(
            '8l {code}.8 1>> {file}'.format(
                code = self._CODE,
                file = self._ERR
            )
        )
        
    def run(self):
        os.system('./8.out > {file}'.format(file = self._RESULT))
        

    def display(self):
        err = open(self._ERR).read()
        
        if (len(err)):
            self.label.setText(err)
        else:
            result = open(self._RESULT).read()
            self.label.setText(result)
        
    def clean(self):
        os.system(
            'rm -rf {err} {result}'.format(
                err = self._ERR, 
                result = self._RESULT
            )
        )

if __name__ == "__main__":
    import sys
    
    app = QtGui.QApplication(sys.argv)
    form = Form()
    form.show()
    app.exec_()

